<script setup lang="ts">
import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';
import { cloneDeep } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import {
  meetingNotifyTaskAdd,
  meetingNotifyTaskInfo,
  meetingNotifyTaskUpdate,
} from '#/api/meeting/notify';
import { getDictOptions } from '#/utils/dict';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

import MiniproTemplatePreview from './minipro-template-preview.vue';
import { drawerSchema } from './notify';

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? '编辑消息通知' : '新增消息通知';
});

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  // layout: 'vertical',
  schema: drawerSchema(),
  showDefaultActions: false,
  fieldMappingTime: [
    [
      'auditTime',
      ['auditTimeStart', 'auditTimeEnd'],
      ['YYYY-MM-DD HH:mm:ss', 'YYYY-MM-DD HH:mm:ss'],
    ],
    [
      'enrollTime',
      ['enrollTimeStart', 'enrollTimeEnd'],
      ['YYYY-MM-DD HH:mm:ss', 'YYYY-MM-DD HH:mm:ss'],
    ],
  ],
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicModal, modalApi] = useVbenModal({
  class: 'w-[650px]',
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const { id, meetingId } = modalApi.getData() as {
      id: number | string;
      meetingId: number | string;
    };
    isUpdate.value = !!id;
    await formApi.setFieldValue('meetingId', meetingId);

    formApi.updateSchema([
      {
        fieldName: 'sendType',
        componentProps: {
          onChange: (value: number) => {
            formApi.updateSchema([
              {
                fieldName: 'content',
                description:
                  value === 1
                    ? `如需增加姓名标识，可插入{姓名}符号，如"尊敬的{姓名}，您好！"。`
                    : '所填内容将在微信模板通知中的「温馨提示」字段中显示。',
                componentProps: {
                  maxlength: value === 1 ? 50 : 20,
                },
              },
            ]);
          },
        },
      },
      // {
      //   fieldName: 'templateId',
      //   componentProps: {
      //     onChange: async (value: string) => {
      //       await formApi.setFieldValue('templatePreview', value);
      //     },
      //   },
      // },
      {
        fieldName: 'notifyType',
        componentProps: {
          onChange: async (value: number) => {
            await formApi.setFieldValue('sendRange', undefined);
            if (value === 1) {
              formApi.updateSchema([
                {
                  fieldName: 'sendRange',
                  componentProps: {
                    options: getDictOptions(
                      DictEnum.MEETING_NOTIFY_RANGE_AUDIT,
                      true,
                    ),
                  },
                },
              ]);
            }
            if (value === 2) {
              formApi.updateSchema([
                {
                  fieldName: 'sendRange',
                  componentProps: {
                    options: getDictOptions(
                      DictEnum.MEETING_NOTIFY_RANGE_SIGN,
                      true,
                    ),
                  },
                },
              ]);
            }
          },
        },
      },
    ]);

    if (isUpdate.value && id) {
      const record = await meetingNotifyTaskInfo(id);
      await formApi.setValues(record);
    }
    markInitialized();

    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    const data = cloneDeep(await formApi.getValues());
    await (isUpdate.value
      ? meetingNotifyTaskUpdate(data)
      : meetingNotifyTaskAdd(data));
    console.log(data);
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}
</script>

<template>
  <BasicModal :title="title" class="w-[550px]">
    <BasicForm>
      <template #templatePreview>
        <MiniproTemplatePreview :template-id="formApi.form.values.templateId" />
      </template>
    </BasicForm>
  </BasicModal>
</template>
